package com.zxd.interview.eightthread.stop;

/**
 * 不合适的停止线程的方法
 * 使用volatie
 *
 * @author Xander
 * @version v1.0.0
 * @Package : com.zxd.interview.eightthread.stop
 * @Description : 不合适的停止线程的方法
 * @Create on : 2023/3/8 13:41
 **/
public class UnsuitableVolatieStopThread implements Runnable {

    private volatile boolean is_stop = false;

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new UnsuitableVolatieStopThread());
        thread.start();
        Thread.sleep(2000);
        thread.interrupt();
    }

    @Override
    public void run() {
        int num = 0;
        while (true && !is_stop) {
            if (num % 100 == 0) {
                System.out.println("100的倍数" + num);
            }
            num++;
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                is_stop = true;
                e.printStackTrace();
            }
        }
        System.out.println("程序正常退出");

    }/**
     通常情况下使用volatile变量可以实现和在exception内继续中断的处理
     100的倍数1000
     100的倍数1100
     100的倍数1200
     100的倍数1300
     java.lang.InterruptedException: sleep interrupted
     at java.lang.Thread.sleep(Native Method)
     at com.zxd.interview.eightthread.stop.UnsuitableVolatieStopThread.run(UnsuitableVolatieStopThread.java:33)
     at java.lang.Thread.run(Thread.java:750)
     程序正常退出

    */
}
